﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// using System.Web.Mvc;
using Keepo.Models;
using Keepo.Models.Services;
using System.IO;
using System.Xml.Serialization;
using Infrastructure.Data;

namespace Keepo.Helpers
{
    public class TemplateHelper
    {
        static public void toXml()
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var templates = repository.GetAll<DesignTemplate>().ToList();

                List<DesignTemplateExport> export = new List<DesignTemplateExport>();
                templates.ForEach(m => export.Add(new DesignTemplateExport(m)));

                StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("~/resources/initializers/templates.xml"));
                XmlSerializer xmlSerialize = new XmlSerializer(export.ToArray().GetType());
                xmlSerialize.Serialize(sw, export.ToArray());
                sw.Close();
                sw.Dispose();
            }
        }

        static public void fromXml()
        {
            DesignTemplateExport[] designTemplates = new DesignTemplateExport[] { };

            XmlSerializer xmlSerialize = new XmlSerializer(designTemplates.GetType());
            StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath("~/resources/initializers/templates.xml"));
            designTemplates = (xmlSerialize.Deserialize(sr) as DesignTemplateExport[]);

            foreach (var template in designTemplates)
            {
                createDesignTemplate(template);
            }
        }

        // Create new Template and return ID
        static public int createDesignTemplate(DesignTemplateExport template)
        {
            using (GenericRepository repository = new GenericRepository())
            {
                DesignTemplate designTemplate = template.toEntity();

                if (UserHelper.IsLogon())
                {
                    designTemplate.UserId = UserHelper.CurrentUser().UserId;
                }
                else
                {
                    designTemplate.CookieGuid = CookieGuidAttribute.getGuid();
                }

                // TBD TMP Assign bakcground color
                Random rnd = new Random();
                int numColors = repository.Count<ProductColor>();
                int colorId = rnd.Next(numColors) + 1;
                ProductColor productColor = repository.GetByKey<ProductColor>(colorId);
                designTemplate.BackgroundRgb = productColor != null ? productColor.RGB : 0;

                //default values
                designTemplate.ModifiedDate = DateTime.Now;
                designTemplate.Views = 0;
                designTemplate.Description = "תבנית חדשה הכוללת איור מדהים";

                repository.Add<DesignTemplate>(designTemplate);
                repository.UnitOfWork.SaveChanges();

                foreach (TemplatePageExport page in template.Pages)
                {
                    page.DesignTemplateId = designTemplate.DesignTemplateId;
                    repository.Add<TemplatePage>(page.toEntity());
                }

                repository.UnitOfWork.SaveChanges();

                return designTemplate.DesignTemplateId;
            }
        }

        static public DesignTemplateExport[] getTemplatesByCategoryId(int categoryId, string orderBy = "None")
        {
            using (GenericRepository repository = new GenericRepository())
            {
                DesignTemplate[] templates;

                TemplateCategory templateCategory = repository.GetByKey<TemplateCategory>(categoryId);
                //if selected category is "User"
                if (templateCategory.TemplateCategoryId == 1)
                {
                    if (UserHelper.IsLogon())
                    {
                        int userId = UserHelper.CurrentUser().UserId;
                        templates = repository.Find<DesignTemplate>(m => m.TemplateCategoryId == categoryId && m.UserId == userId).ToArray();
                    }
                    else
                    {
                        string cookieGuid = CookieGuidAttribute.getGuid();
                        templates = repository.Find<DesignTemplate>(m => m.TemplateCategoryId == categoryId && m.CookieGuid == cookieGuid).ToArray();
                    }

                }
                //if selected category is regular category
                else
                {
                    templates = repository.Find<DesignTemplate>(m => m.TemplateCategoryId == categoryId).ToArray();
                }

                return OrderTemplates(templates, orderBy);
            }
        }

        static public DesignTemplateExport[] getTemplatesByBackgroundRgb(int backgroundRgb, string orderBy = "None")
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var templates = repository.Find<DesignTemplate>(m => m.BackgroundRgb == backgroundRgb).ToArray();

                return OrderTemplates(templates, orderBy);
            }
        }

        static private DesignTemplateExport[] OrderTemplates(DesignTemplate[] templates, string orderBy)
        {
            var orderedTemplates = templates.OrderBy(t => t.ModifiedDate);

            switch (orderBy)
            {
                case "Popular":
                    orderedTemplates = templates.OrderByDescending(t => t.Views);
                    break;

                case "Random":
                    orderedTemplates = templates.OrderBy(t => Guid.NewGuid());
                    break;

                case "None":
                    break;
            }

            return orderedTemplates.Select(template => new DesignTemplateExport(template)).ToArray();
        }

        static public DesignTemplateExport[] getTemplatesByKeyword(string keyword, string orderBy = "None")
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var templates = repository.Find<DesignTemplate>(m => m.TemplateCategoryId != 1 && m.Title.Contains(keyword)).ToArray();

                return OrderTemplates(templates, orderBy);
            }
        }

        static public DesignTemplateExport[] getTemplatesByHot(string orderBy = "None")
        {
            using (GenericRepository repository = new GenericRepository())
            {
                var templates = repository.Find<DesignTemplate>(m => m.IsHighlighted).ToArray();

                return OrderTemplates(templates, orderBy);
            }
        }

    }
}
